package AgentTravel.Behaviours;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import AgentTravel.MyOntology;
import AgentTravel.LogicObjects.City;
import AgentTravel.LogicObjects.UserProfile;
import AgentTravel.Messages.RequestVisitMessage;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

public class HostGetRequestsBehaviour extends CyclicBehaviour 
{
	UserProfile profile;
	AID serverAgent;
	
	public HostGetRequestsBehaviour(UserProfile profile, AID serverAgent)
	{
		this.profile=profile;
		this.serverAgent=serverAgent;
	}
	
	@Override
	public void action() 
	{
		MessageTemplate mt=MessageTemplate.MatchPerformative(ACLMessage.REQUEST);
		mt=MessageTemplate.or(mt, MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
		mt=MessageTemplate.or(mt, MessageTemplate.MatchPerformative(ACLMessage.REJECT_PROPOSAL));
		ACLMessage msg = myAgent.receive(mt);
		
		
		if (msg != null) 
		{		
			// dostalem zapytanie o profil
			if(msg.getContent().equals(MyOntology.requestProfileText))
			{
				System.out.println("HOST: Dostalem zapytanie o profil");
				ACLMessage reply=msg.createReply();
				try 
				{
					reply.setContentObject(profile);
				} 
				catch (IOException e) 
				{
					e.printStackTrace();
				}
				reply.setPerformative(ACLMessage.INFORM_REF);
				myAgent.send(reply);
			}	
			// dostalem zapytanie o wizyte
			else if(msg.getPerformative()==ACLMessage.PROPOSE)
			{
				System.out.println("HOST: Dostalem zapytanie o wizyte");
				
				RequestVisitMessage rvm=null;
				
				try 
				{
					rvm=(RequestVisitMessage)msg.getContentObject();
					myAgent.addBehaviour(new HostGetReservationBehaviour(msg.getSender(), rvm.visitTime,serverAgent));
					
				} 
				catch (UnreadableException e) 
				{
					System.err.println("Nie taki mial byc obiekt");
				}
			}
			//odwolano wizyte
			else if(msg.getPerformative()==ACLMessage.REJECT_PROPOSAL)
			{
				//TODO: tutaj dac znac serwerowi
				ACLMessage discard=new ACLMessage(ACLMessage.REJECT_PROPOSAL);
				discard.addReceiver(serverAgent);
				try {
					discard.setContentObject(msg.getContentObject());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnreadableException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				myAgent.send(discard);
			}
			
		}
		else 
		{
			block();
		}
		
	}
	
}
